package com.litong.litongjiaoyu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.litong.litongjiaoyu.entity.StudentAttendance;
import com.litong.litongjiaoyu.entity.WxMaTemplateData;
import com.litong.litongjiaoyu.entity.WxMssVo;
import com.litong.litongjiaoyu.service.CommenService;
import com.litong.litongjiaoyu.service.StudentAttendanceService;
import com.litong.litongjiaoyu.utils.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 学生考勤控制层
 *
 * @author jingzepei
 * @since 2020-05-21 17:28:48
 */
@RestController
@RequestMapping("studentAttendance")
public class StudentAttendanceController {

    /**
     * 门面模式
     */
    private Logger logger = LoggerFactory.getLogger(StudentAttendanceController.class);

    /**
     * 服务对象
     */
    @Resource
    private StudentAttendanceService studentAttendanceService;

    @Resource
    private CommenService commenService;

    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;

    /**
     * 通过主键查询所有数据
     *
     * @param phone 手机号
     * @return 相关的所有数据
     */
    @GetMapping("query/{phone}")
    public JSONResult select (@PathParam("phone") String phone) {
        return JSONResult.ok(this.studentAttendanceService.queryById(phone));
    }


    /**
     * 考勤信息记录
     * @param jsonObject 考勤信息
     * @return
     */
    @ResponseBody
    @PostMapping("/signIn")
    public JSONResult signIn (@RequestBody JSONObject jsonObject) {
        java.util.Date nowDate = new java.util.Date();

        JSONArray jsonArray = jsonObject.getJSONArray("signIn");

        //将json数组转化为列表
        List<StudentAttendance> studentAttendances = JSON.parseArray(jsonArray.toJSONString(), StudentAttendance.class);

        for (StudentAttendance studentAttendance : studentAttendances) {
            studentAttendance.setDatetime(nowDate);

            studentAttendance.setStatus(studentAttendance.isChecked() ? "在上课中" : "未在课堂");
        }
        

        //由多线程发送微信订阅信息
        sendMessage(studentAttendances, "wx78763b2bea2646c2", "571a3836b6b557d2e7dc1aaeabdc0be2", nowDate);

        //将考勤信息添加到数据库中
        return JSONResult.ok(studentAttendanceService.addInBulk(studentAttendances,
                jsonObject.getString("className"),
                jsonObject.getString("campus")
        ));

    }


    /**
     * 用多线程的形式发送微信订阅消息
     * @param studentAttendances 要发送的所有内容
     * @param appid appid
     * @param appSecret appsecret
     */
    @Async
    public synchronized void sendMessage (List<StudentAttendance> studentAttendances , String appid, String appSecret,
                                          Date nowDate) {
        logger.info("批量发送微信订阅消息之学生考勤");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));


        //发送微信订阅消息
        Map<String, WxMaTemplateData> data = null;

        WxMssVo wxMssVo = new WxMssVo();

        //设置模板ID
        wxMssVo.setTemplate_id("z0cpWVEbVpqP2k2pzljjMdQ0sOyASR9M5ZAgDXv1LJ4");
        //设置要跳转的页面
        wxMssVo.setPage("pages/bar/bar?PageCur=my");

        for (StudentAttendance studentAttendance : studentAttendances) {
            data = new HashMap<>(4);

            //名字
            WxMaTemplateData name = new WxMaTemplateData();
            name.setValue(studentAttendance.getName());
            data.put("name1", name);

            //时间
            WxMaTemplateData date = new WxMaTemplateData();
            date.setValue(simpleDateFormat.format(nowDate));
            data.put("date2", date);

            //地点
            WxMaTemplateData location = new WxMaTemplateData();
            location.setValue(studentAttendance.getCampus());
            data.put("thing3", location);

            //状态
            WxMaTemplateData status = new WxMaTemplateData();
            status.setValue(studentAttendance.getStatus());
            data.put("phrase4", status);

            //设置接收人openid
            wxMssVo.setTouser(commenService.getOpenId(studentAttendance.getPhone()));

            //设置要发送的数据
            wxMssVo.setData(data);

            //发送
            JSONObject result = wxPushServiceQcl.pushOneUser(appid, appSecret, wxMssVo);
        }
    }
}